/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DialogoLogin.java
 *
 * Created on 28-feb-2013, 19:54:46
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.Usuarios;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.SQLUtil;
import com.camachosanchez.util.seguridad.Encriptador;
import java.awt.event.KeyEvent;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.util.Properties;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.UIManager;

/**
 *
 * @author Rolando
 */
public class DialogoLogin extends javax.swing.JFrame {

    /** Creates new form DialogoLogin */
    public DialogoLogin() {
//        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        this.setSize(400, 350);
//        setAlwaysOnTop(true);
        leerDatosInicio();
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlBackground = new com.camachosanchez.gui.PanelLogin();
        btnIngresar = new javax.swing.JButton();
        btnCancelar = new javax.swing.JButton();
        pnlIngreso = new javax.swing.JPanel();
        pnlEtiquetas = new javax.swing.JPanel();
        lblUsuario = new javax.swing.JLabel();
        lblClave = new javax.swing.JLabel();
        pnlCajasTexto = new javax.swing.JPanel();
        txtUsuario = new javax.swing.JTextField();
        txpClave = new javax.swing.JPasswordField();
        chkRecordar = new javax.swing.JCheckBox();
        lblInformacion = new javax.swing.JLabel();
        lblTitulo = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setBackground(new java.awt.Color(102, 102, 102));
        setUndecorated(true);

        pnlBackground.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(255, 255, 255)));

        btnIngresar.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnIngresar.setText("Ingresar");
        btnIngresar.setOpaque(false);
        btnIngresar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnIngresarActionPerformed(evt);
            }
        });

        btnCancelar.setFont(new java.awt.Font("Tahoma", 1, 12));
        btnCancelar.setText("Cancelar");
        btnCancelar.setOpaque(false);
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        pnlIngreso.setOpaque(false);
        pnlIngreso.setLayout(new java.awt.BorderLayout(5, 5));

        pnlEtiquetas.setOpaque(false);
        pnlEtiquetas.setLayout(new java.awt.GridLayout(2, 1, 20, 20));

        lblUsuario.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblUsuario.setForeground(new java.awt.Color(255, 255, 255));
        lblUsuario.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblUsuario.setText("Usuario:");
        pnlEtiquetas.add(lblUsuario);

        lblClave.setFont(new java.awt.Font("Tahoma", 0, 12));
        lblClave.setForeground(new java.awt.Color(255, 255, 255));
        lblClave.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        lblClave.setText("Contraseña:");
        pnlEtiquetas.add(lblClave);

        pnlIngreso.add(pnlEtiquetas, java.awt.BorderLayout.LINE_START);

        pnlCajasTexto.setOpaque(false);
        pnlCajasTexto.setLayout(new java.awt.GridLayout(2, 1, 20, 20));

        txtUsuario.setFont(new java.awt.Font("Tahoma", 1, 12));
        txtUsuario.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 1));
        txtUsuario.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtUsuarioKeyPressed(evt);
            }
        });
        pnlCajasTexto.add(txtUsuario);

        txpClave.setFont(new java.awt.Font("Tahoma", 1, 12));
        txpClave.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 5, 1, 1));
        txpClave.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txpClaveKeyPressed(evt);
            }
        });
        pnlCajasTexto.add(txpClave);

        pnlIngreso.add(pnlCajasTexto, java.awt.BorderLayout.CENTER);

        chkRecordar.setForeground(new java.awt.Color(255, 255, 255));
        chkRecordar.setText("Recordar contraseña");
        chkRecordar.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        chkRecordar.setOpaque(false);

        lblInformacion.setForeground(new java.awt.Color(255, 255, 255));
        lblInformacion.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblInformacion.setText("Tiresoft™ es un producto de DelawIT | http://tiresoft.delawit.com");

        lblTitulo.setFont(new java.awt.Font("Eras Medium ITC", 1, 18)); // NOI18N
        lblTitulo.setForeground(new java.awt.Color(255, 255, 255));
        lblTitulo.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        lblTitulo.setText("CAMACHO SÁNCHEZ LOGISTICS");

        javax.swing.GroupLayout pnlBackgroundLayout = new javax.swing.GroupLayout(pnlBackground);
        pnlBackground.setLayout(pnlBackgroundLayout);
        pnlBackgroundLayout.setHorizontalGroup(
            pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlBackgroundLayout.createSequentialGroup()
                .addGroup(pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlBackgroundLayout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(lblInformacion, javax.swing.GroupLayout.PREFERRED_SIZE, 381, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBackgroundLayout.createSequentialGroup()
                        .addGap(9, 9, 9)
                        .addGroup(pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(pnlBackgroundLayout.createSequentialGroup()
                                .addGap(58, 58, 58)
                                .addGroup(pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                    .addGroup(pnlBackgroundLayout.createSequentialGroup()
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(btnIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                        .addComponent(btnCancelar, javax.swing.GroupLayout.DEFAULT_SIZE, 115, Short.MAX_VALUE))
                                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addGroup(pnlBackgroundLayout.createSequentialGroup()
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 130, javax.swing.GroupLayout.PREFERRED_SIZE)
                                            .addComponent(chkRecordar))
                                        .addComponent(pnlIngreso, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.PREFERRED_SIZE, 257, javax.swing.GroupLayout.PREFERRED_SIZE)))
                                .addGap(66, 66, 66))
                            .addComponent(lblTitulo, javax.swing.GroupLayout.DEFAULT_SIZE, 382, Short.MAX_VALUE))))
                .addContainerGap())
        );

        pnlBackgroundLayout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnCancelar, btnIngresar});

        pnlBackgroundLayout.setVerticalGroup(
            pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlBackgroundLayout.createSequentialGroup()
                .addContainerGap(76, Short.MAX_VALUE)
                .addComponent(lblTitulo, javax.swing.GroupLayout.PREFERRED_SIZE, 37, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pnlIngreso, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(chkRecordar, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(pnlBackgroundLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 39, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnIngresar, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(32, 32, 32)
                .addComponent(lblInformacion)
                .addContainerGap())
        );

        pnlBackgroundLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {btnCancelar, btnIngresar});

        getContentPane().add(pnlBackground, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
// TODO add your handling code here:
    System.exit(0);
}//GEN-LAST:event_btnCancelarActionPerformed

private void btnIngresarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnIngresarActionPerformed
// TODO add your handling code here:
    autenticar();
}//GEN-LAST:event_btnIngresarActionPerformed

    private void txpClaveKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txpClaveKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            autenticar();
        }
    }//GEN-LAST:event_txpClaveKeyPressed

    private void txtUsuarioKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtUsuarioKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txpClave.requestFocusInWindow();
            txpClave.selectAll();
        }
    }//GEN-LAST:event_txtUsuarioKeyPressed

    private void autenticar() {
        try {
            String user = txtUsuario.getText();
            char[] input = txpClave.getPassword();
            String clave = "";
            for (int i = 0; i < input.length; i++) {
                clave += input[i];
            }
            Usuarios usuario = SQLUtil.autenticar(user, Encriptador.encriptar(clave, Constantes.LLAVE));
            if (usuario != null) {
                setVisible(false);
                dispose();
                Constantes.currentUser = usuario;
                Principal.getInstance().setInformacionUsuario(txtUsuario.getText());
                escribirDatosInicio();
            } else {
                JOptionPane.showMessageDialog(this, "Usuario y/o contraseña incorrectos.", "Datos incorrectos", JOptionPane.ERROR_MESSAGE);
                txtUsuario.requestFocusInWindow();
                txtUsuario.selectAll();
            }
        } catch (GeneralSecurityException ex) {
            ex.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    private void leerDatosInicio() {
        InputStream is = null;
        Properties prop = new Properties();
        try {
            is = new FileInputStream("tiresoft.properties");
            prop.load(is);
            String strUsuario = prop.getProperty("usuario");
            String strClave = prop.getProperty("password");
            String strRecordado = prop.getProperty("recordar");
            if (strRecordado.compareTo("SI") == 0) {
                txtUsuario.setText(strUsuario);
                txpClave.setText(Encriptador.desencriptar(strClave, Constantes.LLAVE));
                chkRecordar.setSelected(true);
            }
            is.close();
        } catch (Exception e) {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    private void escribirDatosInicio() {
        try {
            Properties prop = new Properties();
            prop.setProperty("usuario", txtUsuario.getText());
            char[] input = txpClave.getPassword();
            String clave = "";
            for (int i = 0; i < input.length; i++) {
                clave += input[i];
            }
            prop.setProperty("password", Encriptador.encriptar(clave, Constantes.LLAVE));
            prop.setProperty("recordar", chkRecordar.isSelected() ? "SI" : "NO");
            FileOutputStream os = new FileOutputStream("tiresoft.properties");
            prop.store(os, "");
            os.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        JFrame.setDefaultLookAndFeelDecorated(true);
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                DialogoLogin dialog = new DialogoLogin();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnCancelar;
    private javax.swing.JButton btnIngresar;
    private javax.swing.JCheckBox chkRecordar;
    private javax.swing.JLabel lblClave;
    private javax.swing.JLabel lblInformacion;
    private javax.swing.JLabel lblTitulo;
    private javax.swing.JLabel lblUsuario;
    private com.camachosanchez.gui.PanelLogin pnlBackground;
    private javax.swing.JPanel pnlCajasTexto;
    private javax.swing.JPanel pnlEtiquetas;
    private javax.swing.JPanel pnlIngreso;
    private javax.swing.JPasswordField txpClave;
    private javax.swing.JTextField txtUsuario;
    // End of variables declaration//GEN-END:variables
}
